<template>
  <div class='container'>
    <el-card class="box-card">
  <div class="clearfix">
    <span>卡片名称</span>
  </div>
    <el-form  label-width="100px" class="demo-ruleForm" :model="forminfo" :rules="qsRules" ref="from">

   <el-form-item label="学科" prop="subjectID">
    <el-select  placeholder="请选择" v-model="forminfo.subjectID" @change="changeSubject">
      <el-option v-for="item in subjectju" :key="item.value" :label="item.label" :value="item.value"></el-option>

    </el-select>
  </el-form-item>
  <el-form-item label="目录" prop="catalogID">
    <el-select  placeholder="请选择" v-model="forminfo.catalogID" >
      <el-option v-for="item in catalogOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>

    </el-select>
  </el-form-item>
  <el-form-item label="企业" prop="enterpriseID">
    <el-select  placeholder="请选择" v-model="forminfo.enterpriseID">
      <el-option v-for="item in tenterprise" :key="item.id" :value="item.id" :label="item.company" ></el-option>
    </el-select>
  </el-form-item>

  <el-form-item label="城市" prop="city" >

           <el-select  placeholder="请选择" v-model="forminfo.city" @change="getcity">
             <!-- 城市1 -->
      <el-option v-for="item in getcitys" :key="item" :label="item" :value="item"></el-option>
    </el-select>

             <!-- 城市2 -->
          <el-select  placeholder="请选择" v-model="forminfo.province">
            <el-option v-for="item in areaOptions" :key="item" :label="item" :value="item"></el-option>

          </el-select>

  </el-form-item>
    <el-form-item label="方向" prop="direction">
    <el-select  placeholder="请选择"  v-model="forminfo.direction">
      <el-option v-for="item in directions" :key="item" :label="item" :value="item"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="题型" prop="questionType">：
      <el-radio-group v-model="forminfo.questionType" @change="changeRadio({})">

    <el-radio v-for="item in questionType" :key="item.value" :label="item.value+''" >{{item.label}}</el-radio>

  </el-radio-group>
  </el-form-item>
    <el-form-item label="难度" prop="difficulty">：
      <el-radio-group v-model="forminfo.difficulty">

    <el-radio v-for="item in difficulty" :key="item.value" :label="item.value+''" >{{item.label}}</el-radio>

  </el-radio-group>
  </el-form-item>
  <!-- foeminfo的对象以上 -->
<el-form-item label="题干" prop="question">
   <quill-editor v-model="forminfo.question" :options="editorOptions" @blur="changegit"></quill-editor>
</el-form-item>
<!-- 选项 需要分情况和试题类型关联-->
        <el-form-item label="选项" prop="options"  v-if="forminfo.questionType !== '3'">
          <div class="option_item" v-for="item in forminfo.options" :key="item.code" >
            <el-radio style="margin-right:0" v-if="forminfo.questionType === '1'" @change="changeRadio(item)" v-model="item.isRight" :label="true"> {{item.code}}：</el-radio>
            <el-checkbox  style="margin-right:0" v-if="forminfo.questionType ==='2'" v-model="item.isRight" :label="true">{{item.code}}：</el-checkbox>
            <el-input v-model="item.title" style="width:240px"></el-input>

            <el-upload
          action="#"
          :limit="3"
          list-type="picture-card"
          :http-request="(obj)=>{uploadSuccess(item,obj)}"
          :class="{myupload:item.img}"
          :on-remove="(file, fileList)=>{handleRemove(item,file, fileList)}">
          上传图片
        </el-upload>
          </div>
          <!-- 添加按钮 -->
          <el-button type="danger" :disabled="forminfo.questionType !=='2'" size="small" @click="addmument">+增加选项与答案</el-button>
        </el-form-item>
 <!-- <el-button type="danger" icon="el-icon-plus" disabled> 增加选项与答案</el-button> -->
<el-form-item label="解析视屏">
<el-input v-model="forminfo.videoURL"></el-input>
</el-form-item>
<el-form-item label="答案解析" prop="question">
   <quill-editor v-model="forminfo.answer" :options="editorOptions"></quill-editor>
</el-form-item>
<el-form-item label="题目备注">
  <el-input
  type="textarea"
  :rows="3"
   v-model="forminfo.remarks"
  placeholder="请输入内容"
  >
</el-input>
</el-form-item>
  <el-form-item label="试题标签：">
            <el-select
              style="width:400px"
              v-model="forminfo.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择试题标签">
      <el-option v-for="item in tagsOptions" :key="item.value" :label="item.label" :value="item.label"></el-option>

    </el-select>
  </el-form-item>

 <el-button type="primary" @click="addbute()">确认提交</el-button>
 <el-button type="primary">确认</el-button>
</el-form>
</el-card>

  </div>
</template>

<script>
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import { simple as getsubject } from '@/api/hmmm/subjects.js'
import { simple as getcutabject } from '@/api/hmmm/directorys.js'
import { list as getenterprise } from '@/api/hmmm/companys.js'
import { provinces as getCityOptions, citys as getAreaOptions } from '@/api/hmmm/citys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
// import { getToken } from '@/utils/auth.js'
import { simple as getTagOptions } from '@/api/hmmm/tags.js'
import { add, detail } from '@/api/hmmm/questions.js'
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
var cos = new COS({
  SecretId: 'AKIDKUO3RYPyGH2WjfJhoeDWXHkwsWu0qPhh',
  SecretKey: 'lFRM1OUJr9CyUkUx94j7D3cuvf9MIxLS'
})
export default {
  data () {
    return {
      // token: getToken(),
      // 富文本高亮
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      // 数据对象
      forminfo: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        city: '', // 城市1
        province: '', // 城市2
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        videoURL: '', // 视频
        // answer: '', // 答案解析
        options: [// 选项
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
        // 校验规则
      },
      qsRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ]
      },
      subjectju: [], // 学科渲染
      catalogOptions: [], // 目录渲染
      tenterprise: [], // 企业管理
      getcitys: getCityOptions(), // 城市
      areaOptions: [], // 地区
      directions: direction, // 方向
      questionType, // 题型
      difficulty, // 难度
      tagsOptions: [] // 标签简单列表
    }
  },
  created () {
    // this.getcitys = this.provinces
    this.lpopll()
    this.lpopmm()
    this.gethuju()
    if (this.$route.query.id) {
      this.getQuestion()
    }
    console.log(this.$route)
  },

  methods: {
    // 确认提交
    addbute () {
      this.$refs.from.validate(async boo => {
        if (boo) {
          const data = { ...this.forminfo }
          console.log(data)
          data.tags = data.tags.join(',')
          await add(data)
          this.$message.success('添加成功')
          // this.$route.push('/questions/list')
        }
      })
    },
    // 腾讯云
    handleRemove (item, file, fileList) {
      item.img = ''
    },
    uploadSuccess (item, obj) {
    // obj.file为文件对象 等于files[0]
      // console.log(item)
      // console.log(obj.file)
      cos.putObject({
        Bucket: 'hrljz-1309363298', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: +new Date() + obj.file.name, /* 必须 唯一值，必须是字符串 */
        StorageClass: 'STANDARD',
        Body: obj.file, // 上传文件对象0
        onProgress: (progressData) => {
          // console.log(progressData)
          // console.log(+new Date())
          // console.log(JSON.stringify(progressData))
        }
      }, function (err, data) {
        console.log(2)
        console.log(err || data)
        item.img = 'http://' + data.Location
      })
    },

    // 基础题库详情
    async getQuestion () {
      const { data } = await detail({ id: this.$route.query.id })
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.forminfo = data
      const res = await getcutabject({ subjectID: this.forminfo.subjectID })
      this.catalogOptions = res.data
      const res2 = await getTagOptions({ subjectID: this.forminfo.subjectID })
      this.tagsOptions = res2.data
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    // 学科
    async lpopll () {
      const { data } = await getsubject()
      this.subjectju = data

      // console.log(data)
    },
    // 目录渲染
    async changeSubject (subjectID) {
      const data = await getcutabject({ subjectID: this.forminfo.subjectID })
      this.catalogOptions = data.data
    },
    // 标签简单列表
    async gethuju () {
      const res = await getTagOptions()
      // console.log(res)
      this.tagsOptions = res.data
    },
    // 企业
    async lpopmm () {
      const data = await getenterprise({ pagesize: 10000 })
      this.tenterprise = data.data.items
    },
    async getcity (val) {
      const data = await getAreaOptions(val)
      this.areaOptions = data
    },
    // 题干：
    changegit () {
      this.$refs.from.validateField('question')// validateField 校验  question  字段
    },
    // 选择题型
    changeRadio (item) {
      // 清除选项
      this.forminfo.options.forEach(item => {
        item.isRight = false
      })
      // console.log(item)
      item.isRight = true
    },
    // 提交复杂选择项
    addmument () {
      // 总结 code = String.fromCharCode(index + 65)
      this.forminfo.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.forminfo.options.length),
        title: '',
        img: ''
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.myupload .el-upload--picture-card {
    display: none;
  }
</style>
